var fieldJobId;
var changeFromClick = false;
// var reBackNodeText;
// 初始化数据
var parameterData = [ {
	valueCode : '0',
	valueName : '默认参数'
}, {
	valueCode : '1',
	valueName : '自定义参数'
} ];
// 定位显示
var arrayLi = [];
var arrayLiInd = 0;
var requestmsgfinal = "";
// var requestmsg = "";
// var parapair = [];
var resultSysNum = 0;
var loadSysNum = 0;
$(document)
		.ready(
				function() {
					$("#divDatagrid").show();
					$("#divTextArea").hide();
					$("#ff input").val("");
					$("#ff :input").bind('change', function() {
						$("#ff").data("changed", true);
					});
					// 参数模型下拉框
					$('#comboxParameterModel').combobox(
							{
								valueField : 'valueCode',
								textField : 'valueName',
								editable : false,
								value : "0",
								data : parameterData,
								onSelect : function(record) {
									if ("0" == record.valueCode) {
										$("#divDatagrid").show();
										$("#divTextArea").hide();
										$("#trParameter4Sended").show();
										$("#txtParameter4Sended").val(
												$("#txtRequestMessId").val());
										parapair = [];
									} else {
										$("#divDatagrid").hide();
										$("#divTextArea").show();
										$("#trParameter4Sended").hide();
										$("#txtAreaSelfDefineParameter").val(
												$("#txtRequestMessId").val());
										requestmsg = requestmsgfinal;

									}
								}
							});

					// 接口请求参数
					$("#datagrid")
							.datagrid(
									{
										url : BASE_URL_INTERFACE_PARAMETER_SEARCH
												+ '/findByExample?v='
												+ Math.random(),
										method : 'get',
										autoRowHeight : true,
										singleSelect : true,
										striped : true,
										nowrap : false,
										columns : [ [
												{
													field : 'dataTypeName',
													title : '参数类型',
													width : 80
												},
												{
													field : 'name',
													title : '参数名称',
													width : 100
												},
												{
													field : 'value',
													title : '参数值',
													width : 235,
													formatter : function(value,
															rowData, rowIndex) {
														var type = $("#txtInterfaceType").val();
														var request=$("#txtRequest").val();
														//是REST接口并且是GET请求方式，则将参数加到URL后面
														if('2'==type &&'0'==request){
															var url = $(
																	"#txtPriUrl")
																	.val();
															if (url != ''
																	&& url != null) {
																if (url.indexOf('?') < 0) {
																	url += '?';
																}else{
																	url += '&';
																}
																url += rowData.name+ "="+ value;
																$("#txtPriUrl")
																		.val(url);
															}
														}
														return "<input type='text' value='"+value+"'  onChange='changeParamCallback("
																+ rowIndex
																+ ",$(this).val());' style='width: 225px;' class='text' name='paraValue' />";
													}
												},
												{
													field : 'isNeed',
													title : '参数是否必须',
													width : 80,
													formatter : function(value,
															rowData, rowIndex) {
														if (value == true) {
															parapair[parapair.length] = {
																name : rowData.name,
																value : ''
															};
															return "<input type='checkbox' name='isNeed' disabled = false checked=true />";
														}
														return "<input type='checkbox' name='isNeed' disabled = false/>";
													}
												} ] ],
										pagination : false,
										loadFilter : function(data) {
											// alert("inData:"+JSON.stringify(data));
											return {
												total : data.totalElements,
												rows : data.content
											};
										},
										onBeforeLoad : function(param) {
											param.page -= 1;
											param.size = param.rows;
											delete param.rows;
											// 默认取请求参数
											param.type = '1';
											param.sort = 'createTime,desc';
											var interfaceId = $(
													'#txtInterfaceId').val();
											if (interfaceId != "") {
												param.interfaceId = interfaceId;
											}

											var interfaceName = $(
													'#txtInterfaceName').text();
											if (interfaceName != "") {
												param.interfaceName = interfaceName;
											}
										},
										onLoadSuccess : function() {
											var type = $("#txtInterfaceType")
													.val();
											if ('1'==type) {
												setDefaultParameter();
											}
										}
									});
				});

$("#searchNode").click(
		function(e) {
			if ($("#systemName").val() != '') {
				// 后台查询匹配的接口
				$.ajax({
					url : BASE_URL_HTTP_INTERFACE
							+ '/findHttpInterfaceByIfName' + '?ifName='
							+ encodeURI($("#systemName").val()) + '&v=' + Math.random(),
					dataType : 'json',
					type : 'get',
					success : function(data) {
						if (data.backValue == true) {
							var system = data.httpDatas;
							if (system.indexOf(",") != -1) {
								var systems = system.split(",");
							} else {
								var systems = [ system ];
							}
							resultSysNum = systems.length;
							loadSysNum = 0;
							for (var i = 0; i < systems.length; i++) {
								// 展开系统的节点
								// 找到树的所有节点
								var nodes = $('#tt').tree('getChildren');
								for (var j = 0; j <= nodes.length; j++) {
									if (nodes[j].text == systems[i]) {
										var $self = $(nodes[j].target).find(
												"span.tree-fieldSys");
										if ($self.length) {
											expendNode(nodes[j]);
										} else {
											loadSysNum++;
											if (loadSysNum >= resultSysNum) {
												choose_tree();
											}
										}
										break;
									}
								}

							}

						} else {
							$.messager.alert("错误", "<p>没有找到包含  "
									+ $("#systemName").val() + " 的接口！ </p>",
									"error");
						}
					},
					error : function() {
						$.messager.alert("错误",
								"<p>服务异常，查询接口信息失败，请重新登录或稍后再试！ </p>", "error");
					}
				});
			} else {
				// 搜索关键字为空时，不进行搜索
				/*
				 * $("input").val(""); var row = $('#tt li .tree-node');
				 * row.removeClass('tree-node-selected');
				 */
				$(".tree_con").scrollTop(0);
			}
		});
$("#systemName").bind('input propertychange', function() {
	if (changeFromClick) {
		changeFromClick = false;
		return;
	}
	arrayLi = [];
	arrayLiInd = 0;
	resultSysNum = 0;
	loadSysNum = 0;
	if ($("#systemName").val() != '') {
		// choose_tree();
	} else { // 搜索关键字为空时，不进行搜索
		/*
		 * $("#ff input").val(""); var row = $('#tt li .tree-node');
		 * row.removeClass('tree-node-selected');
		 */
		$(".tree_con").scrollTop(0);
	}
});
$(document, "#systemName").keyup(function(event) {
	if (event.keyCode == 13) {
		$("#searchNode").trigger("click");
	}
});

function expendNode(node) {
	var $self = $(node.target).find("span.tree-collapsed");
	if (!$self.length) {
		return;
	}
	$self.removeClass('tree-collapsed').addClass('tree-expanded');
	$.ajax({
		url : BASE_URL_TREE + '/getHttpBySystemIdForScan?systemId=' + node.id,
		dataType : 'json',
		type : 'get',
		success : function(data) {
			// alert(data)
			$('#tt').tree('append', {
				parent : $self.parent()[0],
				data : data
			});
			loadSysNum++;
			if (loadSysNum >= resultSysNum) {
				choose_tree();
			}
		},
		error : function() {
			loadSysNum++;
			if (loadSysNum >= resultSysNum) {
				choose_tree();
			}
		}
	});
}
function getSelected() {
	var node = $('#tt').tree('getSelected');
	if (node.nodeType == 'systemInterface') {
		$.ajax({
			url : BASE_URL_BASE_URL_HTTP_INTERFACE_CRUD + '/' + node.id + '?v='
					+ Math.random(),
			dataType : 'json',
			type : 'get',
			contentType : "application/json",
			success : function(data) {
				FormEcho(data);
			},
			error : function() {
				alert("error");
			}

		});
	}
}

function choose_tree() {
	$('#tt').tree('expandAll');
	if (arrayLi.length == 0 && arrayLiInd == 0) {
		var searchVal = $("#systemName").val();
		var row = $('#tt li .tree-node');
		var rowcolumn = $('#tt li .tree-node > .tree-title');
		var i = 0, j = 0;

		// row.removeClass('tree-node-selected');
		row.removeClass('tree-node-hover');
		rowcolumn.each(function(column) {
			var matchVal = $(this).text();
			if (matchVal.indexOf(searchVal) != -1) {
				i++;
				var scrTop = $(".tree_con").scrollTop() + $(this).offset().top
						- parseInt($(".tree_con").css("padding-top"), 10)
						- $(".search-con")[0].offsetHeight
						- $(".left_menu > .menu_tit")[0].offsetHeight;

				if (i <= 1) {
					// $(this).parent().addClass('tree-node-selected');
					$(this).parent().addClass('tree-node-hover'); // 改成鼠标hover状态，不选中搜索结果

					$(".tree_con").scrollTop(scrTop);
					arrayLiInd = 1;
					// getSelected();
				}
				arrayLi.push([ matchVal, scrTop ]);
			}
		});
	} else {
		var rowcolumn = $('#tt li .tree-node > .tree-title');
		var row = $('#tt li .tree-node');
		// row.removeClass('tree-node-selected');
		row.removeClass('tree-node-hover');
		if (arrayLiInd < arrayLi.length) {
			rowcolumn.each(function(column) {
				var matchVal = $(this).text();
				if (matchVal == arrayLi[arrayLiInd][0]) {
					// $(this).parent().addClass('tree-node-selected');
					$(this).parent().addClass('tree-node-hover'); // 改成鼠标hover状态，不选中搜索结果
					$(".tree_con").scrollTop(arrayLi[arrayLiInd][1]);
					arrayLiInd++;
					getSelected();
					return false;
				}
			});
		} else {
			// arrayLi = [];
			arrayLiInd = 0;
			$(".tree_con").scrollTop(0);
			choose_tree();
		}
	}
}
// 表单数据回显
function FormEcho(data) {
	// clear form
	parapair = [];
	$("#txtInterfaceId").val("");
	$("#txtInterfaceCode").val("");
	$("#txtInterfaceName").text("");
	$("#txtRequestUrl").val("");
	$("#txtRequest").val("");
	$("#txtDataFormate").val("");
	$("#txtInterfaceType").val("");
	$("#txtRequestMessId").val("");
	$("#txtAuthType").val("");
	$("#txtContentType").val("");
	$("#txtSystemCode").val("");
	$("#txtVersion").val("");
	$("#txtResult").text("");
	$("#txtPriUrl").val("");
	$("#txtAreaInterfaceDescription").val("");
	$("#txtParameter4Sended").val("");
	$("#txtOperationType").val("");
	$("#txtSoapActionUri").val("");
	// $('#datagrid').datagrid('loadData',{total:0,rows:[]});

	if (data == null || data == "") {
		return;
	}
	var type = data.type;
	var priUrl = data.priUrl;
	if (priUrl != null && priUrl != '') {
		priUrl = priUrl.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
	}
	$("#txtInterfaceId").val(data.id);
	$("#txtInterfaceCode").val(data.code);
	$("#txtInterfaceName").text(data.name);
	$("#txtPriUrl").val(priUrl);
	$("#txtRequest").val(data.request);
	$("#txtDataFormate").val(data.dataFormate);
	$("#txtInterfaceType").val(type);
	$("#txtRequestMessId").val(data.requestMess);
	$("#txtAuthType").val(data.authType);
	$("#txtContentType").val(data.contentType);
	$("#txtSystemCode").val(data.systemCode);
	$("#txtVersion").val(data.version);
	$("#txtParameter4Sended").val($("#txtRequestMessId").val());
	$("#txtOperationType").val(data.operationType);
	$("#txtSoapActionUri").val(data.soapActionUri);
	requestmsg = data.requestMess;
	requestmsgfinal = data.requestMess;

	$('#datagrid').datagrid('reload');
}

function providerTest() {
	var contentType = $("#txtContentType").val();
	var authType = $("#txtAuthType").val();
	var parameterModel = $('#comboxParameterModel').combobox('getValue');
	var url = $("#txtPriUrl").val();
	var type = $("#txtInterfaceType").val();
	var request = $("#txtRequest").val();
	var dataFormateVal = $("#txtDataFormate").val();
	if (url==null||url == "") {
		$.messager.alert("错误", "<p>接口请求地址不能为空！ </p>", "error");
		return;
	}
	var soapActionUri = $("#txtSoapActionUri").val();
	var operationType = $("#txtOperationType").val();
	var requestMessValue = $("#txtRequestMessId").val();
	var parameters = "";
	if ("0" == parameterModel) {
		parameters = $("#txtParameter4Sended").val();
	} else if ("1" == parameterModel) {
		parameters = $("#txtAreaSelfDefineParameter").val();
	}
	parameters = JSON.stringify(parameters);
	var data = '{"url":"' + url + '","interfaceType":"' + type + '" ,'
			+ '"request":"' + request + '","authType":"' + authType
			+ '","contentType"' + ':"' + contentType + '","parameters"' + ':'
			+ parameters + ',"operationType":' + operationType
			+ ',"soapActionUri":"' + soapActionUri + '"}';
	$("#progressbar, #progressbar_tips").fadeIn();
	loading_point.timer = setInterval(loading, 200);
	$.ajax({
		type : "post",
		url : BASE_URL_API + '/serviceProviderTesting/serviceTesting' + '?v='
				+ Math.random(),
		dataType : 'json',
		data : data,
		contentType : "application/json",
		success : function(data) {
			$("#progressbar, #progressbar_tips").fadeOut();
			clearInterval(loading_point.timer);
			var result = data.result.replace(/&lt;/g, "<")
					.replace(/&gt;/g, ">");
			$("#txtResult").text(result);
		},
		error : function() {
			$("#progressbar, #progressbar_tips").fadeOut();
			clearInterval(loading_point.timer);
			$.messager.alert('错误', '<p>服务异常，服务测试失败，请稍后重试或联系管理员!</p>', 'error');
		}
	});

}

function paraOnblur() {
	// /alert("onblue");
}
function paraOnfocus() {
	// alert("onfocus");
}
//
// $('#username').focus(function ()//得到教室时触发的时间
// {

// 领域系统结构树
var tree_id = '';
var isSave = false;
var modifyNode;
// var reBackNode;
$(".tree_con #tt")
		.tree(
				{
					url : BASE_URL_TREE + '/getHttp4User4EasyUiTree'
							+ '?auditStatus=1&operationType=1&v='
							+ Math.random(),
					lines : false,
					/*
					 * onExpand: function(node) { if(node.nodeType ==
					 * "fieldSystem") { $.ajax({ url :BASE_URL_TREE+
					 * '/getHttpBySystemId?systemId=' + node.id +
					 * '&auditStatus=1&operationType=1', dataType : 'json', type :
					 * 'get', success : function(data){ } }); } },
					 */
					onLoadSuccess : function() {
						$(
								"#tt > li > ul > li > .tree-node > .tree-file, #tt > li > .tree-node > .tree-file")
								.css("background",
										"url('../../../images/st_folder.png') 2px 2px no-repeat");
						var nodes = $('#tt').tree('getChildren');
						function changeNodeClass(nodelist, start, end) {
							if (start < nodelist.length) {
								for (var i = start; i <= end; i++) {
									var node = nodelist[i];
									if (node.nodeType == "fieldSystem"
											&& node.hasChildren
											&& (!node.children || node.children.length == 0)
											&& $(node.target).find(
													".tree-fieldSys").length == 0) {
										$(node.target).find("span.tree-icon")
												.prev().remove();
										$(node.target).children(
												".tree-icon.tree-file")
												.before(
														'<span class="tree-fieldSys tree-collapsed" data-id="'
																+ node.id
																+ '"></span>');
										$(node.target)
												.children(".tree-fieldSys")
												.click(
														function() {

															var $self = $(this);
															if ($self
																	.hasClass('tree-collapsed')) {// alert(node.id+'
																// '+node.text);
																$self
																		.removeClass(
																				'tree-collapsed')
																		.addClass(
																				'tree-expanded');
																// $('#tt').tree('expend',
																// $self.parent()[0])
																$
																		.ajax({
																			url : BASE_URL_TREE
																					+ '/getHttpBySystemId?systemId='
																					+ $self
																							.attr("data-id")
																					+ '&operationType=1',
																			dataType : 'json',
																			type : 'get',
																			success : function(
																					data) {
																				// alert(data)
																				$(
																						'#tt')
																						.tree(
																								'append',
																								{
																									parent : $self
																											.parent()[0],
																									data : data
																								});
																			}
																		});
															} else {
																$self
																		.addClass(
																				'tree-collapsed')
																		.removeClass(
																				'tree-expanded');
																$('#tt')
																		.tree(
																				'collapse',
																				$self
																						.parent()[0]);
															}

														});
									}
									var icons = $(node.target).find(
											"span.tree-icon");
									if (node.nodeType == 'systemInterface') {
										if (node.auditStatus == '0') {
											$(icons[0])
													.removeClass("tree-file");
											$(icons[0]).addClass(
													"icons4unaudit");
										} else if (node.auditStatus == '1') {
											$(icons[0])
													.removeClass("tree-file");
											$(icons[0]).addClass("icons4audit");
										}
									}
								}
								if (end + 1 < nodelist.length) {
									start = end + 1;
									end += 100;
									end = end > nodelist.length - 1 ? nodelist.length - 1
											: end;
									setTimeout(function() {
										changeNodeClass(nodelist, start, end);
									}, 50);
								}
							}
						}
						var end = nodes.length > 100 ? 99 : nodes.length;
						changeNodeClass(nodes, 0, end);
						/*
						 * $.each(nodes,function(i , node) { var icons =
						 * $(node.target).find("span.tree-icon"); if
						 * (node.nodeType == 'systemInterface') {
						 * if(node.auditStatus=='0'){
						 * $(icons[0]).removeClass("tree-file");
						 * $(icons[0]).addClass("icons4unaudit"); } else
						 * if(node.auditStatus=='1'){
						 * $(icons[0]).removeClass("tree-file");
						 * $(icons[0]).addClass("icons4audit"); } } });
						 */
					},
					onBeforeSelect : function(node) {
						if ($(node.target).children(".tree-folder").length) {
							return false;
						}
						if ($(node.target).children("tree-file").length
								&& ($(node.target).parent().parent().parent()
										.parent()[0].id == "tt" || $(
										node.target).parent().parent()[0].id == "tt")) {
							return false;
						}
						return true;
					},
					onClick : function(node) {
						arrayLi = [];
						arrayLiInd = 0;
						changeFromClick = true;
						$("#systemName").val(node.text);
					},
					onSelect : function(node) {
						$("#ff").data("changed", false);
						if (node.nodeType == 'systemInterface') {
							// $(".right_mask").css("display","none");
							fieldJobId = node.id;
							if (tree_id != fieldJobId) {
								tree_id = fieldJobId;
								$("#ff input").val("");
							} else {
								return false;
							}
							var interfaceId;
							$
									.ajax({
										url : BASE_URL_API
												+ '/serviceProviderTesting/getHttpInterfaceInfos?interfaceId='
												+ node.id + '&v='
												+ Math.random(),
										dataType : 'json',
										type : 'get',
										// contentType :
										// "application/json",
										success : function(data) {
											// alert("data:"+JSON.stringify(data));
											FormEcho(data);
										},
										error : function() {
											$.messager
													.alert(
															"错误",
															"<p>服务异常，查询接口信息失败，请重新登录或稍后再试！ </p>",
															"error");
										}
									});
						}
					}
				});
var loading_point = {
	timer : null,
	len : 3,
	count : 0
};
function loading() {
	if (loading_point.count < loading_point.len) {
		loading_point.count++;
		$("#progressbar_point").text($("#progressbar_point").text() + ".");
	} else {
		loading_point.count = 0;
		$("#progressbar_point").text("");
	}
}

/**
 * 参数改变回调函数
 */
function changeParamCallback(rowIndex, value) {
	var row = $('#datagrid').datagrid('getData').rows[rowIndex];
	var name = row.name;
	var type = $("#txtInterfaceType").val();
	var result = null;

	// ws
	if ("1" == type) {
		result = selfDefineParameter(name, value);
		if (result == null) {
			return;
		}
		$("#txtParameter4Sended").val(result);
		$("#txtAreaSelfDefineParameter").val(result);
		
	} else if("2" == type){
		//首先匹配URL参数
		result = urlParameter($("#txtPriUrl").val(),name, value);
		if(result!=null){
			$("#txtPriUrl").val(result);
		}
	}

}

/**
 * 将参数默认值填充到请求报文中
 */
function setDefaultParameter() {
	var rows = $('#datagrid').datagrid('getRows');
	if (rows == null) {
		return;
	}
	var result = requestmsg;
	var temp = "";
	var name = "";
	var value = "";
	$.each(rows, function(i, row) {
		name = row.name;
		value = row.value;
		if (value == null || value == '') {
			return;
		}
		temp = selfDefineParameter(name, value);
		if (temp != null && temp != '') {
			result = temp;
		}
	});
	if (result == null || result == '') {
		return;
	}
	$("#txtParameter4Sended").val(result);
	$("#txtAreaSelfDefineParameter").val(result);
}
